﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;

namespace DatabaseSynchronizer
{
    public class Service
    {
        private readonly string _filePath;

        public Service() {
            _filePath = Assembly.GetEntryAssembly().Location.TrimEnd((Assembly.GetEntryAssembly().ManifestModule).Name.ToCharArray()) + @"DBSSettings.xml";
        }
        

        public Settings GetSettings()
        {
            var settings = LoadSettings();

            if (settings == null)
            {
                settings = new Settings();
                settings.LoggedInUser = Environment.UserName;
                settings.MachineName = Environment.MachineName;
                settings.IsTFS = true;
            }

            return settings;

        }

        private Settings LoadSettings()
        {
            Settings result = null;

            if (File.Exists(_filePath))
            {
                StreamReader streamReader = new StreamReader(_filePath);

                if (streamReader.Peek() != -1)
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Settings));
                    try
                    {
                        result = xmlSerializer.Deserialize(streamReader) as Settings;
                        streamReader.Close();
                    }
                    catch(Exception ex) 
                    {
                        try
                        {
                            //Delete if file can not be deserialized
                            streamReader.Close();
                            File.Delete(_filePath);
                        }
                        catch { }
                    }
                }
            }

            return result;
        }

        public void SaveSettings(Settings settings)
        {
            StreamWriter streamWriter = new StreamWriter(_filePath);
            XmlSerializer xmlSerializer = new XmlSerializer(settings.GetType());

            xmlSerializer.Serialize(streamWriter, settings);
            streamWriter.Flush();
            streamWriter.Close();
        }
    }
}
